/*
 * @filename SecurityUtils.java
 * @author barry
 * @version 0.0.1
 * @date 2019年12月9日
 */
package com.bnzj.core.web.security.util;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.bnzj.core.util.SpringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.bnzj.core.web.security.WebUserDetailsService;
import com.bnzj.core.web.security.handler.DelegatingAuthenticationParseFilter;

/**
 * @author barry
 * @date 2019-12-09
 */
public class SecurityUtils {

    public static final Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /***
     * 获取登录用户所拥有的角色
     * @return
     */
    public static final List<String> getCurrentUserRoleList() {
        Collection<? extends GrantedAuthority> authorities = getAuthentication().getAuthorities();
        return authorities.parallelStream().map(authority -> authority.getAuthority()).collect(Collectors.toList());
    }


    /**
     * 获取当前登录用户
     * @return
     */
    public static final UserDetails getCurrentUser() {
        Authentication authentication = getAuthentication();
        DelegatingAuthenticationParseFilter parser = SpringUtils.get(DelegatingAuthenticationParseFilter.class);
        String username = parser.getUserName(authentication);
        WebUserDetailsService securityUserService = SpringUtils.get(WebUserDetailsService.class);
        return securityUserService.getByUsername(username);
    }

    /**
     * 加密密码
     *
     * @param rawPassword
     * @return
     */
    public static final String encode(String rawPassword) {
        return SpringUtils.get(PasswordEncoder.class).encode(rawPassword);
    }
}
